package com.mayuanfei.springioc;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Bean容器
 *
 * @author 老马
 * @date 2023-01-30 17:16
 */
public class BeanContext {
    public Map<String, Object> beansMap = new ConcurrentHashMap<String, Object>();

    /**
     * 构造方法.把配置文件的类路径传入
     *
     * @param classPath 类路径文件名
     */
    public BeanContext(String classPath) {
        InputStream resource = BeanContext.class.getClassLoader().getResourceAsStream(classPath);
        Document document = XmlUtil.readXML(resource);
        List<Element> elements = XmlUtil.getElements(XmlUtil.getRootElement(document), "bean");
        for (Element element : elements) {
            beansMap.put(element.getAttribute("id"),
                    ReflectUtil.newInstance(element.getAttribute("clazz")));
        }

    }

    /**
     * 获得Bean实例对象
     *
     * @param id bean的id
     * @return 实例对象
     */
    public Object getBean(String id) {
        if (beansMap.containsKey(id)) {
            return beansMap.get(id);
        }
        return null;
    }
}